package com.shujia.flink.window;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

public class Demo2CountWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> linesDS = env.socketTextStream("master", 8888);

        DataStream<Tuple2<String, Integer>> kvDS = linesDS
                .map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(kv -> kv.f0);

        /*
         * 统计窗口
         * countWindow(10)：滚动的统计窗口， 每个key每隔10条数据计算一次
         * countWindow(10, 2): 滑动的统计窗口，每隔两条数据计算最近10条数据
         */
        WindowedStream<Tuple2<String, Integer>, String, GlobalWindow> countWindowDS = keyByDS
                .countWindow(10, 2);

        countWindowDS.sum(1).print();


        env.execute();


    }
}
